package com.example.code.service;

import com.example.code.dao.CodeMapper;
import com.example.code.feign.EmailFeign;
import com.example.common.Code;
import com.example.common.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kangshuai
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class CodeServiceImpl implements CodeService {

    private final int number = 1000;

    @Resource
    private CodeMapper codeMapper;

    @Resource
    private EmailFeign emailFeign;

    @Override
    public Boolean createCode(String email) throws Exception {
        //创建6位随机数
        Integer number = (int) (Math.random() * (999999 - 100000 + 1) + 100000);

        Code code = new Code();
        code.setEmail(email);
        code.setCode(number.toString());
        long now = System.currentTimeMillis();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        code.setCreateTime(sf.format(new Date(now)));
        code.setExpireTime(sf.format(new Date(now + 600000)));

        //存储code到数据库中
        try {
            codeMapper.insertCode(code);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("code存储失败",e.getMessage());
            return false;
        }
        //调用email服务
        boolean result = emailFeign.sendEmail(email, number.toString()).getData();
        return result;
    }

    @Override
    public ResultMessage<Boolean> verifyCode(String email, String code) throws Exception {
        Code queryCode = new Code();
        queryCode.setCode(code);
        queryCode.setEmail(email);
        Code result = codeMapper.queryCode(queryCode);
        if (result == null) {
            return ResultMessage.error("验证码错误", false);
        }

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 日期转换为时间戳
        Date time = sf.parse(result.getExpireTime());
        long timestamp = time.getTime();
        if (timestamp < (System.currentTimeMillis() / number)) {
            return ResultMessage.error("验证码已过期", false);
        }
        return ResultMessage.success(true);
    }
}
